from flask import jsonify, request
from sqlalchemy import or_

from common.libs.UrlManager import UrlManager
from web.models.food.Food import Food
from web.models.food.FoodCat import FoodCat
from web.views.api import route_api


@route_api.route("/food/index")  # /api/food/index
def foodIndex():
    """提供小程序端美食页面的接口函数"""
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    # 【一】 美食轮播图数据
    # 返回销量前三的美食数据
    food_list = Food.query.filter_by(status=1).order_by(Food.total_count.desc(),
                                                        Food.id.desc()).limit(3).all()
    data_food_list = []  # 返回的数据格式化，就是json格式的数据
    if food_list:
        for item in food_list:
            tmp_data = {
                'id': item.id,
                'pic_url': UrlManager.buildImageUrl(item.main_image)
            }
            data_food_list.append(tmp_data)
    resp['data']['banner_list'] = data_food_list  # 轮播图数据
    # 【二】 美食分类数据
    cat_list = FoodCat.query.filter_by(status=1).order_by(FoodCat.weight.desc()).all()
    data_cat_list = []
    data_cat_list.append({
        'id': 0,
        'name': "全部"
    })
    if cat_list:
        for item in cat_list:
            tmp_data = {
                'id': item.id,
                'name': item.name
            }
            data_cat_list.append(tmp_data)
    resp['data']['cat_list'] = data_cat_list  # 美食分类
    return jsonify(resp)


@route_api.route("/food/search")
def foodSearch():
    """为小程序端提供搜索美食列表的接口函数"""
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    # 取得小程序端传递过来的查询参数
    req = request.values
    # 美食分类id
    cat_id = int(req['cat_id']) if 'cat_id' in req else 0
    # 搜索关键字
    mix_kw = str(req['mix_kw']) if 'mix_kw' in req else ''
    # 页码
    p = int(req['p']) if 'p' in req else 1
    if p < 1:
        p = 1
    # 每一页美食数量
    page_size = 10
    offset = (p - 1) * page_size
    query = Food.query.filter_by(status=1)
    # 查询美食类别
    if cat_id > 0:
        query = query.filter_by(cat_id=cat_id)
    # 查询美食关键字
    if mix_kw:
        rule = or_(Food.name.ilike("%{0}%".format(mix_kw)), Food.tags.ilike("%{0}%".format(mix_kw)))
        query = query.filter(rule)
    food_list = query.order_by(Food.total_count.desc(), Food.id.desc()).offset(offset).limit(page_size).all()
    # 转格式  [food,food]==>[{},{}]
    data_food_list = []
    if food_list:
        for item in food_list:
            tmp_data = {
                'id': item.id,
                'name': "%s" % (item.name),
                'price': str(item.price),
                'min_price': str(item.price),
                'pic_url': UrlManager.buildImageUrl(item.main_image)
            }
            data_food_list.append(tmp_data)
    resp['data']['list'] = data_food_list
    resp['data']['has_more'] = 0 if len(data_food_list) < page_size else 1
    return jsonify(resp)


@route_api.route("/food/info")
def foodInfo():
    """为小程序端提供获取美食详情的接口函数"""
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    id = int(req['id']) if 'id' in req else 0
    food_info = Food.query.filter_by(id=id).first()
    if not food_info or not food_info.status:  # 没有找到商品或者状态已经删除
        resp['code'] = -1
        resp['msg'] = "美食已下架"
        return jsonify(resp)
    resp['data']['info'] = {  # 详情页信息
        "id": food_info.id,
        "name": food_info.name,
        "summary": food_info.summary,
        "total_count": food_info.total_count,
        "comment_count": food_info.comment_count,
        'main_image': UrlManager.buildImageUrl(food_info.main_image),
        "price": str(food_info.price),
        "stock": food_info.stock,
        "pics": [UrlManager.buildImageUrl(food_info.main_image)]
    }
    return jsonify(resp)
